package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.FavoristTagNewAdapter;
import com.fancon.android.gardenjokesx.adapter.UserNewAdapter;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.entity.UserNews;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;

/**
 * New Screen
 * 
 * @author chutieucodon
 * 
 */
public class U21_22Activity extends GardenJokesBaseActivity {

	private Button mBtnYou;
	private Button mBtnFavorist;
	private ArrayList<UserNews> mListNew;
//	private ArrayList<FavourisTagsNews> mListFavoristTag;
	private ListView mList;
	private UserNewAdapter mAdapter;
	private FavoristTagNewAdapter mAdapterTag;
//	private PullToRefreshListView mRefreshList;
	private int indexList, topList;
	boolean isRefresh = false;
	boolean isBtnYouClick = false;
	boolean isBtnFavoristClick = false;
	private String userID;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.u21_22);

//			if (MessageReceiver.numberNotify != 0) {
//				MessageReceiver.numberNotify = 0;
//				NotificationManager mNotificationManager = (NotificationManager) U21_22Activity.this
//						.getSystemService(Context.NOTIFICATION_SERVICE);
//				mNotificationManager.cancelAll();
//				System.out.println("U21_22: Clear Notify of Meshtiles");
//			}

			User user = UserUtil.getInfoUserLogin(getApplicationContext());
			if (user != null) {
				userID = user.getUser_id();
			}
			SharedPreferences settings = getSharedPreferences(
					Constant.PREFS_REGISTER, 0);
			SharedPreferences.Editor edit = settings.edit();
			edit.putInt(Constant.BADGE_NUMBER, 0);
			edit.commit();
			mBtnYou = (Button) findViewById(R.id.U21_btnYou);
			mBtnFavorist = (Button) findViewById(R.id.U21_btnFavorist);
			mList = (ListView) findViewById(R.id.u21_22_listNEW);
			mList.setDivider(null);
			setOnClick(mBtnYou);
			setOnClick(mBtnFavorist);
			ListUserNewRequest request = new ListUserNewRequest("U21",
					U21_22Activity.this);
			getGlobalState().getRequestQueue().addRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param v
	 *            : View clickabled
	 */
	private void setOnClick(View v) {
		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.U21_btnYou:
					dismissProgress();

					isBtnYouClick = true;
					isBtnFavoristClick = false;
					ListUserNewRequest request = new ListUserNewRequest("U21",
							U21_22Activity.this);
					getGlobalState().getRequestQueue().addRequest(request);
					break;
				case R.id.U21_btnFavorist:
					dismissProgress();

					isBtnFavoristClick = true;
					isBtnYouClick = false;
					ListFavoristTagRequest request2 = new ListFavoristTagRequest(
							"U22", U21_22Activity.this);
					getGlobalState().getRequestQueue().addRequest(request2);
					break;
				default:
					break;
				}
			}
		});

	}

	private class ListUserNewRequest extends RequestUI {

		private Activity context;
		//private FanconProgressBar mProgressDialog;

		public ListUserNewRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			// mProgressDialog =
			// MeshProgressBar.show(context.getParent()!=null?context.getParent():context,
			// context.getString(R.string.common_loading));
			showProgress(context.getString(R.string.common_loading));
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			try {
				if (mAdapter == null || isRefresh == true)
					getUserNew(userID);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}

		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try {
				dismissProgress();
				if (mAdapter == null) {
					mAdapter = new UserNewAdapter(U21_22Activity.this, mListNew);
					Log.d("list request", "set adapter");
					mList.setAdapter(mAdapter);
				} else {
					mList.setAdapter(mAdapter);
					mAdapter.notifyDataSetChanged();
					mList.setSelectionFromTop(indexList, topList);
				}

				//mRefreshList.onRefreshComplete();
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	private class ListFavoristTagRequest extends RequestUI {

		private Activity context;
//		private FanconProgressBar mProgressDialog;

		public ListFavoristTagRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			// mProgressDialog =
			// MeshProgressBar.show(context.getParent()!=null?context.getParent():context,
			// context.getString(R.string.common_loading));
			showProgress(context.getString(R.string.common_loading));

			//mRefreshList.removeNoHit();
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			try {
				if (mAdapterTag == null || isRefresh == true)
					getFavoristTag(userID);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try {
				dismissProgress();

				// mProgressDialog.dismiss();
//
//				mBtnYou.setBackgroundResource(R.drawable.common_btn_top_1);
//				mBtnYou.setTextColor(getResources().getColor(R.color.white));
//				mBtnFavorist
//						.setBackgroundResource(R.drawable.common_btn_top_active_1);
//				mBtnFavorist.setTextColor(getResources().getColor(
//						R.color.orange));
//				isRefresh = false;
//				mRefreshList.setTime(TimeUtil.getLastRefresh(
//						getApplicationContext(), Constant.U22));
//				if (mListFavoristTag.size() == 0) {
//					mRefreshList.setNoHit();
//				} else {
//					mRefreshList.removeNoHit();
//				}
//				if (mAdapterTag == null) {
//					mAdapterTag = new FavoristTagNewAdapter(
//							U21_22Activity.this, mListFavoristTag);
//					Log.d("list request", "set adapter");
//					mList.setAdapter(mAdapterTag);
//				} else {
//					mList.setAdapter(mAdapterTag);
//					mAdapterTag.notifyDataSetChanged();
//					mList.setSelectionFromTop(indexList, topList);
//				}
//				mRefreshList.onRefreshComplete();
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	private void getUserNew(String userID) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("user_id", userID));
		GardenJokesApiConnect api = new GardenJokesApiConnect(U21_22Activity.this);
		String result = api.execGet(getApplicationContext(),
				GardenJokesApiConnect.GROUP_U, "getUserNews", nameValuePairs);
//		TimeUtil.setLastRefresh(getApplicationContext(), Constant.U21);
		Log.d("user new", result);
		JsonPaser json = new JsonPaser();
		mListNew = json.getUserNews(result);
		Log.d("size list new", mListNew.size() + "");
		for (int i = 0; i < mListNew.size(); i++) {
			getListSameNew(i);
		}
	}

	private void getFavoristTag(String userID) {
//		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
//		nameValuePairs.add(new BasicNameValuePair("user_id", userID));
//		ApiConnect api = new ApiConnect(U21_22Activity.this);
//		String result = api.execGet(getApplicationContext(),
//				ApiConnect.GROUP_U, "getNewsOfFavourisTags", nameValuePairs);
//		TimeUtil.setLastRefresh(getApplicationContext(), Constant.U22);
//		Log.d("favorist tag", result);
//		JsonPaser json = new JsonPaser(getApplicationContext());
//		mListFavoristTag = json.getNewsOfFavourisTags(result);
	}

	/**
	 * Tim cac loai tin new giong voi new tai vi tri position trong
	 * mListUser,tim thay thi remove khoi mListUser!
	 * 
	 * @param position
	 * @param index
	 */
	public void getListSameNew(int position) {
		ArrayList<UserNews> mTempUser = new ArrayList<UserNews>();
		int typeP, typeT;
		int index;

		String contentP, contentT;
		String photoP, photoT;
		for (index = position + 1; index < mListNew.size(); index++) {
			boolean ok = true;
			typeP = mListNew.get(position).getType();
			typeT = mListNew.get(index).getType();
			contentP = mListNew.get(position).getContent();
			contentT = mListNew.get(index).getContent();
			photoP = mListNew.get(position).getObject_id();
			photoT = mListNew.get(index).getObject_id();
			if ((typeP == 1) && (typeP == typeT)
					&& (contentT.equals(contentP) && (photoT.equals(photoP)))) {
				if (mTempUser.size() > 0) {
					for (int j = 0; j < mTempUser.size(); j++) {
						if (mListNew.get(index).getUser_name()
								.equals(mTempUser.get(j).getUser_name())) {
							// mTempUser.add(mListUser.get(index));
							ok = false;
						}
					}
					if (ok) {
						mTempUser.add(mListNew.get(index));
					}
				} else {
					mTempUser.add(mListNew.get(index));
				}
				// mTempUser.add(mListUser.get(index));
				mListNew.remove(index);
				index--;
			}
		}
		mListNew.get(position).setNews(mTempUser);
	}

}
